package org.mokusakura.web.controller;

import org.mokusakura.constant.ServletUrlConstant;
import org.mokusakura.constant.SessionAttributeKeyConstant;
import org.mokusakura.domain.User;
import org.mokusakura.persistence.Util.RedirectUtil;
import org.mokusakura.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class CartController {
    public static final String PARAMETER_KEY_ITEM_ID_TO_REMOVE = "itemId";
    public static final String ITEM_ID_TO_UPDATE = "id";
    public static final String NEW_QUANTITY_TO_UPDATE = "newQuantity";
    public static final String PARAMETER_KEY_ITEM_ID_TO_ADD = "itemID";
    @Autowired
    private UserService userService;

    @GetMapping(ServletUrlConstant.REMOVE_ITEM_SERVLET_URL)
    public String removeItemFromCart(@SessionAttribute(SessionAttributeKeyConstant.LOGIN_USER) User user,
                                     @RequestParam(PARAMETER_KEY_ITEM_ID_TO_REMOVE) String itemId) throws Exception {
        return userService.deleteItem(user, itemId).equals(1) ? "true" : "false";
    }


    @GetMapping(ServletUrlConstant.UPDATE_QUANTITY_SERVLET_URL)
    public Object updateQuantity(@RequestParam(ITEM_ID_TO_UPDATE) String itemId,
                                 @RequestParam(NEW_QUANTITY_TO_UPDATE) Integer newQty,
                                 @SessionAttribute(SessionAttributeKeyConstant.LOGIN_USER) User user) throws Exception {
        int res = userService.updateCartItemQuantity(user, itemId, newQty);
        return res == 1 ? "true" : "false";
    }

    @GetMapping(ServletUrlConstant.CART_SERVLET_URL)
    public void addItemToCart(HttpServletRequest req, HttpServletResponse resp,
                              @SessionAttribute(SessionAttributeKeyConstant.LOGIN_USER) User loginUser,
                              @RequestParam(PARAMETER_KEY_ITEM_ID_TO_ADD) String itemId) {

        try {
            if (itemId != null) {
                userService.addItemToCart(loginUser, itemId);
            }
            RedirectUtil.sendRedirect(req, resp, ServletUrlConstant.CART_PAGE_SERVLET_URL, false);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
